#include "twi.h"
#include <stdio.h>
#include "time0.h"
#include "f1c100s_gpio.h"
#include "f1c100s_clock.h"

Twi_handle_def twi2_handle = {.instance = TWI2, .clock = 400000, .device_addr = 0x14, .reg_size = 16};
Twi_handle_def twi0_handle = {.instance = TWI0, .clock = 400000, .device_addr = 0x50, .reg_size = 8};
Twi_handle_def ad24c02_handle = {.instance = TWI0, .clock = 400000, .device_addr = 0x50, .reg_size = 8};

void twix_init()
{
    delay(500);
    _TWI2_CLK_ENABLE();

    gpio_init(GPIOE, PIN0 | PIN1, GPIO_MODE_AF4, GPIO_PULL_NONE, GPIO_DRV_3);
    Twi_Reset(&twi2_handle);
    Twi_Init(&twi2_handle);
    Twi_Enable(&twi2_handle);
    uint8_t buf[2] = {0xf3, 0x55};
    Twi_write_reg(&twi2_handle, 0xf533, buf, 2);
    delay(1);
    // twi2_init();
}
uint8_t rxbuf[256];
void twi0_init()
{
    printf("twi0 init.\r\n");
    _TWI0_CLK_ENABLE();
    gpio_init(GPIOD, PIN0 | PIN12, GPIO_MODE_AF3, GPIO_PULL_NONE, GPIO_DRV_3);
    Twi_Reset(&ad24c02_handle);
    Twi_Init(&ad24c02_handle);
    Twi_Enable(&ad24c02_handle);
    uint8_t buf[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJkl";

    Twi_24c02_write(&ad24c02_handle, 0, buf, sizeof(buf));

    // Twi_read_reg(&ad24c02_handle, 0, rxbuf, sizeof(buf));
    // printf("twi0_rx:%s\r\n", rxbuf);
}

void twi0_test(void)
{
    _TWI0_CLK_ENABLE();
    gpio_init(GPIOD, PIN0 | PIN12, GPIO_MODE_AF3, GPIO_PULL_UP, GPIO_DRV_3);
    Twi_Reset(&ad24c02_handle);
    Twi_Init(&ad24c02_handle);
    Twi_Enable(&ad24c02_handle);

    uint8_t rx[10] = {0};
    Twi_24c02_read(&ad24c02_handle, 0, rx, 9);

    printf("\r\nrx: %s\r\n", rx);
}